﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ChoWorkflowServer.Model;
using System.Windows.Interop;
using System.Data;
using Cinchoo.Core;
using Cinchoo.Core.WPF;
using Cinchoo.Core.Windows.Forms;

namespace ChoWorkflowDashboard
{
    /// <summary>
    /// Interaction logic for AddOrEditUserWindow.xaml
    /// </summary>
    public partial class AddOrEditUserWindow : ChoBaseWindowEx
    {
        private readonly IChoDataModel _dataModel = ChoDataModelFactory.New();

        private bool _isDataUpdated;
        internal bool IsDataUpdated
        {
            get { return _isDataUpdated; }
            set 
            { 
                if (value)
                    _isDataUpdated = value; 
            }
        }

        public ChoTasksDataSet.CHO_USERSDataTable UsersTable
        {
            get;
            set;
        }

        public AddOrEditUserWindow()
        {
            using (new ChoWaitCursor())
            {
                UsersTable = _dataModel.GetAllUsers();

                //Add expression columns
                UsersTable.Columns.Add("DISPLAY_NAME", typeof(String), @"FULL_NAME + ' [' + NAME + ']'");

                InitializeComponent();
                this.DataContext = this;
                ComponentDispatcher.ThreadIdle += new EventHandler(ComponentDispatcher_ThreadIdle);
            }
        }

        void ComponentDispatcher_ThreadIdle(object sender, EventArgs e)
        {
            bool isEnabled = lstUsers.SelectedIndex >= 0;

            chkUserEnabled.IsEnabled = isEnabled;
            //txtPassword.IsEnabled = isEnabled;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            _promptSaveChanges = false;
            DialogResult = true;
            //this.Close();
        }

        protected override void RejectChanges()
        {
            UsersTable.RejectChanges();
        }

        protected override bool UpdateChanges()
        {
            return UpdateUsers();
        }

        private bool UpdateUsers()
        {
            try
            {
                _dataModel.UpdateUsers(UsersTable.GetChanges() as ChoTasksDataSet.CHO_USERSDataTable, ChoUser.CurrentUser, Environment.MachineName);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while updating users.{0}{1}.".FormatString(Environment.NewLine, ex.Message),
                    Application.Current.MainWindow.Title, MessageBoxButton.OK, MessageBoxImage.Error);

                return false;
            }
        }

        private void btnNewUser_Click(object sender, RoutedEventArgs e)
        {
            if (txtUserName.Text.Trim().Length == 0) return;

            var x = (from row1 in UsersTable.AsEnumerable<ChoTasksDataSet.CHO_USERSRow>()
                     where row1.NAME == txtUserName.Text
                     select row1).FirstOrDefault();
            if (x != null) return;

            ChoTasksDataSet.CHO_USERSRow row = UsersTable.NewCHO_USERSRow();
            row.ID = -1;
            row.NAME = txtUserName.Text.Trim();
            row.FULL_NAME = txtUserName.Text.Trim();
            //row.PASSWORD = txtPassword.Text.Trim();
            row.ENABLED = true;
            UsersTable.AddCHO_USERSRow(row);

            txtUserName.Text = String.Empty;
            lstUsers.SelectedIndex = lstUsers.Items.Count - 1;
            e.Handled = true;
        }

        protected override bool HasChanges
        {
            get
            {
                DataTable table = UsersTable != null ? UsersTable.GetChanges() : null;
                bool hasChanges = table != null && table.Rows.Count > 0;
                IsDataUpdated = hasChanges;
                return hasChanges;
            }
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            object selectedItem = lstUsers.SelectedItem;
            if (selectedItem == null) return;
            ChoTasksDataSet.CHO_USERSRow row = ((DataRowView)selectedItem).Row as ChoTasksDataSet.CHO_USERSRow;
            if (row == null) return;

            if (MessageBox.Show("Are you sure you want to delete the '{0}' user?".FormatString(row.NAME), Application.Current.MainWindow.Title,
                MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.No)
                return;

            row.Delete();
            e.Handled = true;
        }

        private void txtUserName_GotFocus(object sender, RoutedEventArgs e)
        {
            btnDelete.Visibility = chkUserEnabled.Visibility = lblFullName.Visibility = txtFullName.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void txtUserName_LostFocus(object sender, RoutedEventArgs e)
        {
            btnDelete.Visibility = chkUserEnabled.Visibility = lblFullName.Visibility = txtFullName.Visibility = System.Windows.Visibility.Visible;
        }
    }
}
